<template>
  <div class="product-detail">
    <el-button type="warning" @click="goBack" class="productdet-back-button">{{
      $t("productDet.backToProductList")
    }}</el-button>
    <el-row :gutter="20">
      <el-col :span="8">
        <!-- 大图展示 -->
        <div
          class="big-image-container"
          @mouseenter="showZoom = true"
          @mouseleave="showZoom = false"
          @mousemove="handleMouseMove"
        >
          <el-image
            :src="currentImage"
            fit="contain"
            style="width: 100%; height: 350px"
          >
            <template #zoom>
              <div
                v-if="showZoom"
                class="zoom-container"
                :style="{ left: zoomLeft + 'px', top: zoomTop + 'px' }"
              >
                <el-image
                  ref="zoomResultImg"
                  :src="currentImage"
                  fit="cover"
                  style="
                    width: 300px;
                    height: 300px;
                    transform: scale(2);
                    pointer-events: none;
                  "
                  :style="{
                    marginLeft: -offsetX + 'px',
                    marginTop: -offsetY + 'px',
                  }"
                ></el-image>
              </div>
            </template>
          </el-image>
          <div ref="zoomLens" class="zoom-lens" v-if="showZoom"></div>
        </div>
        <!-- 小图标 -->
        <div class="small-image-list">
          <el-image
            v-for="(image, index) in productImage"
            :key="index"
            :src="image"
            fit="contain"
            style="
              width: 50px;
              height: 50px;
              margin-right: 5px;
              cursor: pointer;
            "
            :class="{ 'selected-image': index === selectedImageIndex }"
            @click="setCurrentImage(index)"
            @mouseenter="setCurrentImage(index)"
          ></el-image>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="merchant-info">
          <!-- 商户图标 -->
          <el-image
            :src="product.logo"
            fit="contain"
            style="width: 50px; height: 50px"
          ></el-image>
          <!-- 商户名称 -->
          <span class="merchant-name">{{
            translatedProduct.storeName || product.storeName
          }}</span>
        </div>
        <h1>{{ translatedProduct.name || product.name }}</h1>
        <div style="margin: 10px 0; display: flex; align-items: center">
          <div style="flex: 1">
            <strong style="color: red; font-size: 30px"
              >￥{{ product.price }}</strong
            >
          </div>
          <div style="flex: 1">
            {{ $t("productDet.stock") }}：{{ product.stock }}
          </div>
        </div>
        <p
          class="product-description"
          v-html="translatedProduct.description || product.description"
        ></p>
        <!-- 添加翻译按钮 -->
        <el-button @click="translateProduct" style="margin-bottom: 5px">{{
          $t("productDet.translate")
        }}</el-button>
        <div style="margin-bottom: 10px; font-size: 15px; color: #8c939d">
          <span>{{ $t("productDet.quantity") }}：</span>
          <el-input-number
            v-model="selectedQuantity"
            :min="1"
            @change="onQuantityChange"
          ></el-input-number>
        </div>
        <div class="btn-group">
          <button
            :loading="isAddingToCart"
            @click="addToCart(product)"
            size="large"
            class="btn-cart"
          >
            {{ $t("productDet.addToCart") }}
          </button>
          <button @click="BuyNow(product)" size="large" class="btn-buy">
            {{ $t("productDet.buyNow") }}
          </button>
          <div class="btn-collect" @click="toggleCollection(product)">
            <el-icon
              class="btn-collect-icon"
              :style="{ color: isCollected ? '#ff5000' : '' }"
              ><Star
            /></el-icon>
            <div
              class="btn-collect-text"
              :style="{ color: isCollected ? '#ff5000' : '' }"
            >
              {{
                isCollected
                  ? $t("productDet.collected")
                  : $t("productDet.collect")
              }}
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import router from "@/router/index.js";
import request from "@/utils/request";
import cat from "@/assets/img/cat.png";

const isAddingToCart = ref(false); // 新增这个响应式数据用于控制按钮加载状态
const isCollected = ref(false);
const userInfo = JSON.parse(localStorage.getItem("xm-pro-user"));
const buyerId = userInfo.id;
console.log("用户 ID:", buyerId);

const product = reactive({
  id: null,
  name: "",
  price: "",
  stock: "",
  category: "",
  description: "",
  imagePath: "",
  state: "",
  // 新增商户图标和名称属性
  storeId: null,
  storeName: "",
  logo: "",
});

// 存储翻译后的商品信息
const translatedProduct = reactive({
  name: "",
  description: "",
  storeName: "",
});

// 加入购物车
const addToCart = (product) => {
  isAddingToCart.value = true; // 设置按钮为加载状态
  console.log("商品 ID:", product.id);
  // 发送 POST 请求，将商品添加到购物车
  request
    .post(`/ShoppingCart/addShoppingCart`, {
      buyerId: buyerId,
      productId: product.id,
      amount: selectedQuantity.value, // 添加 amount 参数
    })
    .then((res) => {
      if (res.msg === "成功") {
        ElMessage({
          message: t("productDet.addSuccess"),
          type: "success",
          duration: 4000, // 提示框显示时长
        });
      } else {
        ElMessage({
          message: t("productDet.addFailed"),
          duration: 3000,
        });
      }
      isAddingToCart.value = false; // 恢复状态
    })
    .catch((error) => {
      console.error(error);
      // 使用Element Plus的警告提示样式，显示黄色的提示框
      ElMessage({
        message: t("productDet.requestFailed"),
        type: "warning",
        duration: 3000,
      });
      isAddingToCart.value = false; // 恢复状态
    });
};

// 立即购买
const BuyNow = (product, quantity) => {
  const orderData = {
    buyerId: buyerId,
    items: {
      [product.id]: selectedQuantity.value,
    },
  };

  const products = [
    {
      productId: product.id,
      productName: product.name,
      productPrice: product.price,
      quantity: selectedQuantity.value,
      imagePath: product.imagePath,
    },
  ];

  router.push({
    path: "payment",
    name: "Payment",
    query: {
      orderData: JSON.stringify(orderData),
      products: JSON.stringify(products),
    },
  });
};

// 切换收藏状态
const toggleCollection = (product) => {
  if (!isCollected.value) {
    console.log("准备添加收藏，商品 ID:", product.id);
    // 加入收藏夹
    request
      .post(`/collect/addCollectsBatch`, {
        buyerId: buyerId,
        productId: [product.id],
      })
      .then((res) => {
        if (res.code === "200") {
          ElMessage({
            message: t("productDet.collectSuccess"),
            type: "success",
            duration: 4000, // 提示框显示时长
          });
          isCollected.value = true;
        }
      })
      .catch((error) => {
        console.error(error);
        ElMessage({
          message: t("productDet.requestFailed"),
          type: "warning",
          duration: 3000,
        });
      });
  }
};

// 获取商品详情
const getProductDetails = (id) => {
  request
    .get(`/product/selectById/${id}`)
    .then((res) => {
      product.id = res.data.id;
      product.name = res.data.name;
      product.price = res.data.price;
      product.stock = res.data.stock;
      product.category = res.data.category;
      product.description = res.data.description;
      product.imagePath = res.data.imagePath;
      product.state = res.data.state;
      // 新增店铺信息赋值
      product.storeId = res.data.storeId;
      product.storeName = res.data.storeName;
      product.logo = res.data.logo;
      // product.total=(product.price * product.num).toFixed(2);
      console.log("商品详情为：", product);

      // 在获取商品详情成功后，设置当前显示的大图
      if (productImage.value.length > 0) {
        currentImage.value = productImage.value[0];
        selectedImageIndex.value = 0;
      }

      // 检查商品是否已经被收藏
      checkIfCollected(product.id);
    })
    .catch((error) => {
      console.error("获取商品详情失败：", error);
    });
};

// 检查商品是否已经被收藏
const checkIfCollected = (productId) => {
  request
    .get(`/collect/selectById/${buyerId}`)
    .then((res) => {
      const collectedProducts = res.data;
      if (collectedProducts.some((item) => item.id === productId)) {
        isCollected.value = true;
      }
    })
    .catch((error) => {
      console.error("检查收藏状态失败：", error);
    });
};

// 使用 computed 来获取图片路径
const productImage = computed(() => {
  if (product.imagePath && product.imagePath.length > 0) {
    const imageFiles = product.imagePath.split(";"); // 将路径分割成数组
    console.log("分割后的图片数组:", imageFiles);
    return imageFiles.map((image) => `${image}`);
  }
  return [];
});
console.log("商品图片路径数组：", productImage.value);

const selectedQuantity = ref(1);
// 处理数字选择器中商品数量的变化
const onQuantityChange = (newQuantity) => {
  selectedQuantity.value = newQuantity;
};

// 放大图像的偏移量
const zoomLeft = ref(0);
const zoomTop = ref(0);
// 放大图像的内部偏移量
const offsetX = ref(0);
const offsetY = ref(0);

// 当前显示的大图
const currentImage = ref("");
// 是否显示放大层
const showZoom = ref(false);
const selectedImageIndex = ref(0);
const setCurrentImage = (index) => {
  currentImage.value = productImage.value[index];
  selectedImageIndex.value = index;
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 引用DOM元素
const bigImage = ref(null);
const zoomLens = ref(null);
const zoomResultImg = ref(null);

// 获取鼠标相对图片的位置
const getCursorPos = (e) => {
  const rect = bigImage.value.getBoundingClientRect();
  return {
    x: e.clientX - rect.left,
    y: e.clientY - rect.top,
  };
};

// 处理鼠标移动事件
const moveLens = (e) => {
  const zoomFactor = 2;
  const lensSize = 100;
  const pos = getCursorPos(e);
  const imageRect = bigImage.value.getBoundingClientRect();
  const imgWidth = imageRect.width;
  const imgHeight = imageRect.height;

  const x = Math.max(lensSize / 2, Math.min(imgWidth - lensSize / 2, pos.x));
  const y = Math.max(lensSize / 2, Math.min(imgWidth - lensSize / 2, pos.y));

  // 更新放大镜位置
  zoomLens.value.style.left = `${x - lensSize / 2}px`;
  zoomLens.value.style.top = `${y - lensSize / 2}px`;

  // 更新放大镜结果显示区域
  zoomResultImg.value.style.left = `${-x * zoomFactor + lensSize / 2}px`;
  zoomResultImg.value.style.left = `${-x * zoomFactor + lensSize / 2}px`;
};

// 翻译商品信息
const translateProduct = () => {
  if (product.id) {
    request
      .get(`/Ai/translate/${product.id}`)
      .then((res) => {
        translatedProduct.name = res.data.name;
        translatedProduct.description = res.data.description;
        translatedProduct.storeName = res.data.storeName;
      })
      .catch((error) => {
        console.error("翻译商品信息失败：", error);
        ElMessage({
          message: "翻译失败，请稍后重试",
          type: "error",
        });
      });
  }
};

onMounted(() => {
  const productId = router.currentRoute.value.params.productId;
  if (productId) {
    getProductDetails(productId);
  }
  if (productImage.value.length > 0) {
    currentImage.value = productImage.value[0];
    selectedImageIndex.value = 0;
  }
});
</script>

<style scoped>
.product-detail {
  padding: 20px;
  height: 100vh;
}

.product-description {
  margin: 10px 0;
  font-size: 16px;
  color: #606266;
}

.productdet-back-button {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.btn-group {
  display: inline-flex;
  border-radius: 4px;
  overflow: hidden;
}
.btn-group button {
  padding: 10px 20px;
  border: none;
  color: white;
  cursor: pointer;
  transition: background-color 0.3s;
}
.btn-group button:first-child {
  border-right: 1px solid rgba(255, 255, 255, 0.3);
}

.btn-group button:hover {
  background-color: #ff5000;
}

.btn-cart {
  background-color: #ffa301;
}
.btn-buy {
  background-color: #ff7200;
}

.btn-collect {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-left: 10px;
  padding: 5px;
}

.btn-collect:hover {
  cursor: pointer;
  color: #ff5000;
}

.btn-collect-icon {
  font-size: 20px;
}
.btn-collect-text {
  font-size: 14px;
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.merchant-name {
  margin-left: 10px;
  font-size: 18px;
  font-weight: bold;
}

.small-image-list {
  display: flex;
  margin-top: 10px;
}

.big-image-container {
  position: relative;
}

.selected-image {
  border: 2px solid #ff5000;
}

.zoom-container {
  position: absolute;
  overflow: hidden;
  z-index: 10;
  pointer-events: none;
}
</style>
